package handler

import (
	"github.com/APP/internal/models"
	"github.com/APP/internal/service/system_service"
	"github.com/APP/internal/utils"
	code "github.com/APP/pkg/response"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

type DictHandler struct {
	dictService system_service.DictService
}

func NewDictHandler() *DictHandler {
	return &DictHandler{
		dictService: system_service.DictService{},
	}
}

// CreateDictRequest 创建字典类型请求结构
type CreateDictRequest struct {
	DictType    string `json:"dict_type" binding:"required"`
	DictName    string `json:"dict_name" binding:"required"`
	Type        int    `json:"type"`
	AllowExtend int    `json:"allow_extend"`
	Status      int    `json:"status"`
	Remark      string `json:"remark"`
}

// UpdateDictRequest 更新字典类型请求结构
type UpdateDictRequest struct {
	DictName    string `json:"dict_name" binding:"required"`
	Type        int    `json:"type"`
	AllowExtend int    `json:"allow_extend"`
	Status      int    `json:"status"`
	Remark      string `json:"remark"`
}

// CreateDictDataRequest 创建字典数据请求结构
type CreateDictDataRequest struct {
	DictType   string         `json:"dict_type" binding:"required"`
	DictCode   string         `json:"dict_code" binding:"required"`
	DictName   string         `json:"dict_name" binding:"required"`
	Sort       int            `json:"sort"`
	Status     int            `json:"status"`
	IsDefault  int            `json:"is_default"`
	Color      string         `json:"color"`
	Icon       string         `json:"icon"`
	Tag        string         `json:"tag"`
	ExtendJson models.JSONMap `json:"extend_json"`
	Remark     string         `json:"remark"`
}

// UpdateDictDataRequest 更新字典数据请求结构
type UpdateDictDataRequest struct {
	DictName   string         `json:"dict_name" binding:"required"`
	Sort       int            `json:"sort"`
	Status     int            `json:"status"`
	IsDefault  int            `json:"is_default"`
	Color      string         `json:"color"`
	Icon       string         `json:"icon"`
	Tag        string         `json:"tag"`
	ExtendJson models.JSONMap `json:"extend_json"`
	Remark     string         `json:"remark"`
}

// DictListRequest 字典列表请求结构
type DictListRequest struct {
	Page     int    `form:"page" binding:"min=1"`
	PageSize int    `form:"page_size" binding:"min=1,max=100"`
	DictType string `form:"dict_type"`
	DictName string `form:"dict_name"`
	Status   *int   `form:"status"`
}

// DictDataListRequest 字典数据列表请求结构
type DictDataListRequest struct {
	Page     int    `form:"page" binding:"min=1"`
	PageSize int    `form:"page_size" binding:"min=1,max=100"`
	DictType string `form:"dict_type"`
	DictCode string `form:"dict_code"`
	DictName string `form:"dict_name"`
	Status   *int   `form:"status"`
}

// CreateDict 创建字典类型
func (h *DictHandler) CreateDict(c *gin.Context) {
	var req CreateDictRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	// 获取当前用户信息
	claims, exists := c.Get("claims")
	var createUser string
	if exists {
		customClaims := claims.(*utils.CustomClaims)
		createUser = customClaims.BaseClaims.Username
	}

	dict := &models.SysDict{
		DictType:    req.DictType,
		DictName:    req.DictName,
		Type:        req.Type,
		AllowExtend: req.AllowExtend,
		Status:      req.Status,
		Remark:      req.Remark,
		CreateUser:  createUser,
		UpdateUser:  createUser,
		CreateTime:  time.Now(),
		UpdateTime:  time.Now(),
	}

	if req.Status == 0 {
		dict.Status = 1 // 默认启用
	}

	createdDict, err := h.dictService.CreateDict(dict)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}

	code.Respond(c, code.Success, createdDict)
}

// UpdateDict 更新字典类型
func (h *DictHandler) UpdateDict(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	var req UpdateDictRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	// 获取当前用户信息
	claims, exists := c.Get("claims")
	var updateUser string
	if exists {
		customClaims := claims.(*utils.CustomClaims)
		updateUser = customClaims.BaseClaims.Username
	}

	dict := &models.SysDict{
		ID:          id,
		DictName:    req.DictName,
		Type:        req.Type,
		AllowExtend: req.AllowExtend,
		Status:      req.Status,
		Remark:      req.Remark,
		UpdateUser:  updateUser,
		UpdateTime:  time.Now(),
	}

	updatedDict, err := h.dictService.UpdateDict(dict)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, updatedDict)
}

// DeleteDict 删除字典类型
func (h *DictHandler) DeleteDict(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	err = h.dictService.DeleteDict(id)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, idStr)
}

// GetDict 获取字典类型详情
func (h *DictHandler) GetDict(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	dict, err := h.dictService.GetDict(id)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, dict)
}

// GetDictList 获取字典类型列表
func (h *DictHandler) GetDictList(c *gin.Context) {
	var req DictListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	// 设置默认值
	if req.Page == 0 {
		req.Page = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 10
	}

	dicts, total, err := h.dictService.GetDictList(req.Page, req.PageSize, req.DictType, req.DictName, req.Status)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}

	result := gin.H{
		"list":      dicts,
		"total":     total,
		"page":      req.Page,
		"page_size": req.PageSize,
	}
	code.Respond(c, code.Success, result)
}

// CreateDictData 创建字典数据
func (h *DictHandler) CreateDictData(c *gin.Context) {
	var req CreateDictDataRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	// 获取当前用户信息
	claims, exists := c.Get("claims")
	var creator string
	if exists {
		customClaims := claims.(*utils.CustomClaims)
		creator = customClaims.BaseClaims.Username
	}

	dictData := &models.SysDictData{
		DictType:   req.DictType,
		DictCode:   req.DictCode,
		DictName:   req.DictName,
		Sort:       req.Sort,
		Status:     req.Status,
		IsDefault:  req.IsDefault,
		Color:      req.Color,
		Icon:       req.Icon,
		Tag:        req.Tag,
		ExtendJson: req.ExtendJson,
		Remark:     req.Remark,
		Creator:    creator,
		CreatedAt:  time.Now(),
	}

	if req.Status == 0 {
		dictData.Status = 1 // 默认启用
	}

	createdDictData, err := h.dictService.CreateDictData(dictData)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, createdDictData)
}

// UpdateDictData 更新字典数据
func (h *DictHandler) UpdateDictData(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	var req UpdateDictDataRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	dictData := &models.SysDictData{
		ID:         id,
		DictName:   req.DictName,
		Sort:       req.Sort,
		Status:     req.Status,
		IsDefault:  req.IsDefault,
		Color:      req.Color,
		Icon:       req.Icon,
		Tag:        req.Tag,
		ExtendJson: req.ExtendJson,
		Remark:     req.Remark,
	}

	updatedDictData, err := h.dictService.UpdateDictData(dictData)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, updatedDictData)
}

// DeleteDictData 删除字典数据
func (h *DictHandler) DeleteDictData(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	err = h.dictService.DeleteDictData(id)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, idStr)
}

// GetDictData 获取字典数据详情
func (h *DictHandler) GetDictData(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	dictData, err := h.dictService.GetDictData(id)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, dictData)
}

// GetDictDataList 获取字典数据列表
func (h *DictHandler) GetDictDataList(c *gin.Context) {
	var req DictDataListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	// 设置默认值
	if req.Page == 0 {
		req.Page = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 10
	}

	dictDataList, total, err := h.dictService.GetDictDataList(req.Page, req.PageSize, req.DictType, req.DictCode, req.DictName, req.Status)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}

	result := gin.H{
		"list":      dictDataList,
		"total":     total,
		"page":      req.Page,
		"page_size": req.PageSize,
	}
	code.Respond(c, code.Success, result)
}

// GetDictDataByType 根据字典类型获取字典数据
func (h *DictHandler) GetDictDataByType(c *gin.Context) {
	dictType := c.Param("type")
	if dictType == "" {
		code.Respond(c, code.ParamError, nil)
		return
	}

	dictDataList, err := h.dictService.GetDictDataByType(dictType)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, dictDataList)
}

// GetDictTypes 获取所有字典类型
func (h *DictHandler) GetDictTypes(c *gin.Context) {
	dictTypes, err := h.dictService.GetDictTypes()
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, dictTypes)
}
